# -*- coding:utf-8 -*-
from fastapi import APIRouter, Request, Depends, UploadFile, File
from core.response import tableinfo, success, fail, file_response
from core.curd import IDList
from core.request import get_page_info, get_query_param
from app.service.system import SysAttachService
from app.entity.system import SysAttach, CreateSysAttach
from config.app import get_config

router = APIRouter()


@router.get('/list')
async def lists(req: Request, page=Depends(get_page_info), where=Depends(get_query_param),
               mService=Depends(SysAttachService.instance)):
    """
        获取测试列表
    """

    total, rows = await mService.select_page(page, where)
    return tableinfo('OK', total, rows)


@router.post('/add')
async def add(req: Request, post: CreateSysAttach, mService=Depends(SysAttachService.instance)):
    """
        添加测试
    """
    one = await mService.insert(post.dict())
    return success('OK', one)


@router.post('/del')
async def remove(req: Request, ids: IDList, mService=Depends(SysAttachService.instance)):
    """
        删除测试
    """
    one = await mService.delete_batch_ids(ids.ids)
    return success('OK')


@router.post('/upload')
async def upload(req: Request, file: UploadFile = File(...), mService=Depends(SysAttachService.instance)):
    res = await mService.upload(file)
    if res is None:
        return fail("上传失败")
    return success('OK', res)


@router.get('/download/{path}')
async def download(req: Request, path: str, mService=Depends(SysAttachService.instance)):
    res: SysAttach = await mService.download(path)
    if res is None:
        return fail("文件下载失败")
    setttings = get_config()

    return file_response(setttings.UPLOAD_PATH + res.path, res.name)
